package com.monster.servlet.user;

import com.alibaba.fastjson.JSON;
import com.monster.pojo.User;
import com.monster.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/pass_login")
public class PassLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        UserServiceImpl usi = new UserServiceImpl();
        Long userId = null;
        String message = null;

        if ((userId = usi.toLogin(phone, password)) != null) {
            String checkbox = request.getParameter("autologin");
            // System.out.println("checkbox="+checkbox);
            // 如果勾选下次自动登录，则将用户ID保存到Cookie中
            if ("0".equals(checkbox)) {
                Cookie[] cookies = request.getCookies();
                for (int i = 0; i < cookies.length; i++) {
                    if ("monster_user".equals(cookies[i].getName())) {
                        cookies[i].setMaxAge(0);    // 删除该Cookie
                        response.addCookie(cookies[i]);
                        break;
                    }
                }
            } else {
                Cookie userCookie = new Cookie("monster_user", userId+"");
                userCookie.setMaxAge(86400 * 7);     // 设置Cookie有效期
                response.addCookie(userCookie);
            }
            User user = usi.getUserById(userId);
            request.getSession().setAttribute("user", user);
            message = JSON.toJSONString(user);
        } else {
            message = "用户名或密码错误";
        }

        PrintWriter out = response.getWriter();
        out.print(message);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
